package main

import (
	"fmt"
	"time"
)

/**
channel tick组合实现的限制并发执行
*/
func main() {
	oneReqPerMilli(500)
	threeReqPerMill(500)
}

/**
每隔500ms执行一次
*/
func oneReqPerMilli(milliseconds int64) {
	request := make(chan int, 5)

	for i := 1; i <= 5; i++ {
		request <- i
	}

	close(request)
	due := time.Duration(milliseconds * time.Millisecond.Nanoseconds())
	limiter := time.Tick(due)

	for req := range request {
		<-limiter
		fmt.Println("oneReqPerMilli request", req, time.Now())
	}

}

/**
刚开始触发三个routine同时执行，之后每隔指定时间执行一个
*/
func threeReqPerMill(milliseconds int64) {
	limiter := make(chan time.Time, 3)

	for i := 0; i < 3; i++ {
		limiter <- time.Now()
	}
	due := time.Duration(milliseconds * time.Millisecond.Nanoseconds())
	go func() {
		for t := range time.Tick(due) {
			limiter <- t
		}
	}()

	request := make(chan int, 10)
	for i := 1; i <= 10; i++ {
		request <- i
	}

	close(request)

	for req := range request {
		<-limiter
		fmt.Println("threeReqPerMill request", req, time.Now())
	}
}
